<?php

namespace common\widgets\pages;

use common\widgets\ButtonDropdown;
use common\widgets\grid\BulkAjaxActionBtn;
use Yii;
use yii\base\Model;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\helpers\Url;

/**
 * Created by PhpStorm.
 * User: brainmix
 * Date: 15/10/24
 * Time: 上午11:47
 */
class GridViewPage extends AdminPage
{
    public $dataProvider;
    /**
     * @var Model $searchModel
     */
    public $searchModel;
    public $tabs;
    public $pageTitle;
    public $tabTitle = "列表";
    public $gridViewActionButtons;

    public $beforeTabsHtml     = "";
    public $afterTabsHtml      = "";
    public $beforeGridViewHtml = "";
    public $afterGridViewHtml  = "";

    /**
     * @return string
     */
    public function getBeforeTabsHtml()
    {
        return $this->beforeTabsHtml;
    }

    /**
     * @param string $beforeTabsHtml
     */
    public function setBeforeTabsHtml($beforeTabsHtml)
    {
        $this->beforeTabsHtml = $beforeTabsHtml;
    }

    /**
     * @return string
     */
    public function getAfterGridViewHtml()
    {
        return $this->afterGridViewHtml;
    }

    /**
     * @param string $afterGridViewHtml
     */
    public function setAfterGridViewHtml($afterGridViewHtml)
    {
        $this->afterGridViewHtml = $afterGridViewHtml;
    }

    /**
     * @return string
     */
    public function getBeforeGridViewHtml()
    {
        return $this->beforeGridViewHtml;
    }

    /**
     * @param string $beforeGridViewHtml
     */
    public function setBeforeGridViewHtml($beforeGridViewHtml)
    {
        $this->beforeGridViewHtml = $beforeGridViewHtml;
    }

    /**
     * @return string
     */
    public function getAfterTabsHtml()
    {
        return $this->afterTabsHtml;
    }

    /**
     * @param string $afterTabsHtml
     */
    public function setAfterTabsHtml($afterTabsHtml)
    {
        $this->afterTabsHtml = $afterTabsHtml;
    }

    /**
     * @var string
     */
    protected $themeViewPath = "@common/views/widgets/pages/";

    /**
     * @var string
     */
    protected $pageViewName = 'grid-view-page';

    const SEARCH_MODEL             = 'searchModel';
    const DATA_PROVIDER            = 'dataProvider';
    const GRID_VIEW_CONFIG         = 'gridViewConfig';
    const GRID_VIEW_ACTION_BUTTONS = 'gridViewActionButtons';


    public function __construct(array $config)
    {
        parent::__construct($config);
        $this->tabs['title'] = isset($this->pageTitle) ? $this->pageTitle :
            method_exists($this->searchModel, "classLabelName") ? $this->searchModel->classLabelName() : $this->searchModel->className();
        $this->tabs['id'] = 'page-tab-' . md5(microtime(true));
        $this->tabs["items"][] = ["label" => $this->tabTitle];
    }


    public function render($params = [])
    {
        if ( ! $this->pageTitle)
        {
            $this->pageTitle = method_exists($this->searchModel, "classLabelName")
                ? $this->searchModel->classLabelName()
                : $this->searchModel->className();
        }
        $gridViewConfig = [
            'id'               => md5($this->searchModel->className()),
            'dataProvider'     => $this->dataProvider,
            'filterModel'      => $this->searchModel,
            'panelTemplate'    => '{items}',
            'hover'            => true,
            'pjax'             => true,
            'toolbar'          => [
                [
                    'content' =>
                        Html::a('<i class="glyphicon glyphicon-plus"></i> ' . Yii::t('common', 'Create'), ['create'], [
                            'data-pjax' => 0,
                            'type'      => 'button',
                            'title'     => Yii::t('kvgrid', 'Add'),
                            'class'     => 'btn btn-success']) . ' ' .
                        Html::a('<i class="glyphicon glyphicon-repeat"></i> ' . Yii::t('common', 'Refresh'), ['index'], [
                            'data-pjax' => 0,
                            'class'     => 'btn btn-default',
                            'title'     => Yii::t('kvgrid', 'Reset Grid')]) .
                        $this->renderGridViewButtons(),
                ],
                '{export}',
                '{toggleData}',
            ],
            'columns'          => $this->searchModel->gridViewColumns(),
            'containerOptions' => ['style' => 'overflow: auto'], // only set when $responsive = false
        ];
        $defaultParams = [
            self::SEARCH_MODEL             => $this->searchModel,
            self::DATA_PROVIDER            => $this->dataProvider,
            self::GRID_VIEW_CONFIG         => $gridViewConfig,
            self::GRID_VIEW_ACTION_BUTTONS => $this->gridViewActionButtons,
            self::TABS                     => $this->tabs,
        ];
        $params = ArrayHelper::merge($defaultParams, $params);
        $params['_page'] = $this;

        return $this->getController()->render($this->getPageViewPath(), $params);
    }

    /**
     * 输出grid-view菜单上的额外菜单项
     *
     * @return string
     * @throws \Exception
     */
    public function renderGridViewButtons()
    {
        $gridViewButtons = "";
        //配置表格右上操作按钮
        if (isset($this->gridViewActionButtons))
        {
            $buttonConfig = [
                'label'    => '操作',
                'options'  => ['class' => "btn-default"],
                'dropdown' => [
                    'items' => $this->gridViewActionButtons
                    //['label' => 'DropdownA', 'url' => '/'],
                    //['content' => 'DropdownA'],
                    ,
                ],
            ];
            if (isset($gridViewActionConfig))
            {
                $buttonConfig = ArrayHelper::merge($buttonConfig, $gridViewActionConfig);
            }
            $gridViewButtons = ButtonDropdown::widget($buttonConfig);
        }

        return $gridViewButtons;
    }

    /**
     * 添加一个GridViewActionBtn
     *
     * @param array $button
     */
    public function addGridViewActionButton(array $button)
    {
        $this->gridViewActionButtons[] = $button;
    }

    public function setGridViewActionButton(array $button)
    {
        $this->gridViewActionButtons = $button;
    }

    public static function genBulkAjaxActionBtn(Model $searchModel, $label, $url)
    {
        return [
            'content' => BulkAjaxActionBtn::widget([
                'gridViewId' => md5($searchModel->className()),
                'btnId'      => 'bulkAjaxActionBtn' . crc32(microtime(true)),
                'label'      => $label,
                'url'        => Url::to($url),
            ]),
            'label' => $label,
        ];
    }
}
